package org.yray.netty.demo;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import org.yray.netty.lengthfield.NettyLengthFieldServerHandler;

public class ChannelDelimiterServer extends ChannelInitializer<SocketChannel> {
    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        //每一个链接过来(每一次创建channel)都会执行这个方法
        System.out.println ("初始化pipeline");
        //编码,将String转码为ByteBuf
        ch.pipeline ().addLast ("encode", new StringEncoder());
        //用分割符处理粘包问题,分隔符可以是多个,
        // 1024代表1024个字节内还没有找到分隔符抛出异常,TooLongFrameException,
        //如果后续的Handler重写了exceptionCaught方法就会调用exceptionCaught方法
        //DelimiterBasedFrameDecoder分割是转义成ByteBuf才分割的,所以如果添加了StringDecoder的话,
        // 要把StringDecoder放在DelimiterBasedFrameDecoder的后面
        ByteBuf delimiter = Unpooled.copiedBuffer ("$_$".getBytes ());
        ch.pipeline ().addLast (new DelimiterBasedFrameDecoder(1024, delimiter));
        //解码,将ByteBuf解码为String
        ch.pipeline ().addLast ("decode", new StringDecoder());
        //handler一般都是放在最后面,建议一个就可以,如果业务复杂拆分多个,那在handler中调用fireXXX才会向下一个handler继续调用
        ch.pipeline ().addLast (new NettyLengthFieldServerHandler());
    }
}
